package com.whccb.apps.office.document.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;

import com.actionsoft.bpms.commons.formfile.model.FormFileModel;
import com.actionsoft.bpms.commons.formfile.model.delegate.FormFile;
import com.actionsoft.bpms.commons.mvc.view.ResponseObject;
import com.actionsoft.bpms.server.fs.DCContext;
import com.actionsoft.bpms.util.UUIDGener;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.local.api.LogAPI;
import com.actionsoft.sdk.local.api.Logger;

public class JodUtil {
	private static final String sourceAppId = "com.actionsoft.apps.jod";
	private static final String aslp = "aslp://com.actionsoft.apps.jod/fileViewUrl";

	private static final Logger logger = LogAPI.getLogger(JodUtil.class);
	
	/**
	 * 将文件转换成PDF文件
	 * @param sid
	 * @param sourceDc
	 * @param formFileId
	 * @param useAppid
	 * @param boid
	 * @param bindid
	 * @param boname
	 * @param pdfFieldName
	 * @return
	 * @throws IOException 
	 */
	public static String fileToPdfAndUrl(String sid, DCContext sourceDc, String formFileId, String useAppid,
			String boid, String bindid, String boname, String pdfFieldName) throws IOException {
		String resultUrl = "";
		if (sourceDc != null) {
			try {
				// 将sourceDc下载到临时目录
				String temPath = sourceDc.getFilePath().substring(0, sourceDc.getFilePath().lastIndexOf("/") + 1);
	
				logger.info("创建PDF,fileToPdfAndUrl，临时目录文件路径为：temPath=" + temPath);
				
				File tempFileDir = new File(temPath);
				if (!tempFileDir.exists()) {
					tempFileDir.mkdirs();
				}
				File temFile = new File(temPath + sourceDc.getFileName());
				
				if (!temFile.exists()) {
					temFile.createNewFile();
				}
				//复制文件
				copyFile(SDK.getDCAPI().read(sourceDc), temFile);
				/**
				 * PDF文件路径
				 */
				String pdfFilePath = temPath + sourceDc.getFileName().substring(0, sourceDc.getFileName().lastIndexOf(".")) + ".pdf";
				
				logger.info("创建PDF,fileToPdfAndUrl,PDF文件路径为：pdfFilePath="+pdfFilePath);
				
				File pdfFile = new File(pdfFilePath);
				if (pdfFile.exists()) {
					pdfFile.delete();
				}
				
				/**
				 * 图片文件路径
				 */
				String pdfImgFilePath = temPath + sourceDc.getFileName().substring(0, sourceDc.getFileName().lastIndexOf("."));
				logger.info("创建PDF,fileToPdfAndUrl,图片文件路径为：pdfImgFilePath="+pdfImgFilePath);
				
				File pdfImgFileDir = new File(pdfImgFilePath);
				
				if (pdfImgFileDir.exists()) {
					// 查询该文件目录下所有文件
					File[] imgFiles = pdfImgFileDir.listFiles();
					if (imgFiles != null && imgFiles.length > 0) {
						for (File imgFile : imgFiles) {
							if (imgFile != null && imgFile.exists() && imgFile.isFile()) {
								imgFile.delete();
							}
						}
					}
				}

				// 根据tempfile生成pdf文件
				Map<String, Object> params = new HashMap<String, Object>();
				// 用户登录账户,必填
				params.put("sid", sid);
				// 源文件路径,必填
				params.put("srcFilePath", temPath + sourceDc.getFileName());
				// 源文件名,必填
				params.put("srcFileName", sourceDc.getFileName());
				// PDF文件路径,必填
				params.put("pdfFilePath", pdfFilePath);
				// PDF图片目录路径,必填
				params.put("origImgFilePath", pdfImgFilePath);
				// 缩略图显示倍数，1表示不缩放，0.3则缩小到30%,非必填
				params.put("zoom", "1");
				ResponseObject ro = SDK.getAppAPI().callASLP(SDK.getAppAPI().getAppContext(sourceAppId), aslp, params);
				if (ro != null && ro.isOk()) {
					resultUrl = ro.get("url") + "";
				}
				// {"data":{"url":"./w?sid=15f20209-4ae8-4b2a-84d7-9496de34842e&cmd=com.actionsoft.apps.jod_fileview&appId=com.actionsoft.apps.jod&fileDirPath=E%3A%2Fpdf%2Fe6ee46d0-eee1-4439-818c-705e1a5c69e0%2FZW&fileName=ZW.doc","maxPageNum":1},"msg":"","id":":RO;","result":"ok"}
				// 将文档转为PDF文档，并生成图片，提供URL访问

				if (pdfFile.exists()) {
					// 将该pdf上传至PDFFILE字段
					List<FormFile> pdfFileList = SDK.getBOAPI().getFiles(boid, pdfFieldName);
					FormFile pdfFormFile = null;
					
					if (CollectionUtils.isNotEmpty(pdfFileList)) {
						pdfFormFile = pdfFileList.get(0);
					} else {
						FormFileModel fm = new FormFileModel();
						fm.setId(UUIDGener.getUUID());
						fm.setAppId(useAppid);
						fm.setCreateDate(new Timestamp(System.currentTimeMillis()));
						fm.setCreateUser("admin");
						fm.setBoId(boid);
						fm.setBoName(boname);
						fm.setFileName(sourceDc.getFileName().substring(0, sourceDc.getFileName().lastIndexOf(".")) + ".pdf");
						fm.setBoItemName(pdfFieldName);
						fm.setProcessInstId(bindid);
						// fm.setTaskInstId(taskid);
						pdfFormFile = fm;
					}
					SDK.getBOAPI().upFile(pdfFormFile, new FileInputStream(pdfFile));
					pdfFile.delete();

				}
			} catch (Exception e) {
				logger.error("将文件转换成PDF文件失败！", e);
				throw new IOException("将文件转换成PDF文件失败！");
			}
		}
		return resultUrl;
	}

	/**
	 * 复制文件
	 * @param inStream
	 * @param targetFile
	 * @throws IOException
	 */
	private static void copyFile(InputStream inStream, File targetFile) throws IOException {
		int byteread = 0;
		if (inStream != null) {
			FileOutputStream fs = null;
			try {
				fs = new FileOutputStream(targetFile);
				byte[] buffer = new byte[inStream.available()];
				while ((byteread = inStream.read(buffer)) != -1) {
					fs.write(buffer, 0, byteread);
				}
			} catch (Exception e) {
				logger.error("JodUtil,copyFile失败！", e);
				throw new IOException("JodUtil,copyFile失败！");
			} finally {
				try {
					fs.close();
					inStream.close();
				} catch (IOException e) {
					logger.error("JodUtil,关闭IO流失败！", e);
					throw new IOException("JodUtil,关闭IO流失败！");
				}
			}
			
			
		}
	}
}
